﻿//***********************************************************************
// Assembly         : phpmk
// Author           : sy
// Created          : 04-02-2010
//
// Last Modified By : sy
// Last Modified On : 04-02-2010
// Description      : 
//
// Copyright        : (c) Another-D-Mention Software. All rights reserved.
//***********************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Compression;

namespace phpmk.ADM.Utils {
    internal static class Pack {

        public static String Compress(String input) {
            if (String.IsNullOrEmpty(input)) {
                return "";
            }

            byte[] buffer = Encoding.ASCII.GetBytes(input);
            MemoryStream memStream = new MemoryStream();
            using (DeflateStream zip = new DeflateStream(memStream, CompressionMode.Compress, true)) {   
                zip.Write(buffer, 0, buffer.Length);
            }

            memStream.Position = 0;

            byte[] compressed = new byte[memStream.Length];
            memStream.Read(compressed, 0, compressed.Length);
            return Convert.ToBase64String(compressed);
        }

        public static String Decompress(String input) {
            if (String.IsNullOrEmpty(input)) {
                return "";
            }
            MemoryStream compressedStream = new MemoryStream(Convert.FromBase64String(input));
            DeflateStream zipStream = new DeflateStream(compressedStream, CompressionMode.Decompress);
            MemoryStream resultStream = new MemoryStream();

            byte[] buffer = new byte[4096];
            int read = 0;

            while ((read = zipStream.Read(buffer, 0, buffer.Length)) > 0) {
                resultStream.Write(buffer, 0, read);
            }

            return Encoding.UTF8.GetString(resultStream.ToArray());
        }
    }
}
